package com.example.mybatis.excutor.statement;
import com.example.mybatis.excutor.Executor;
import com.example.mybatis.mapping.BoundSql;
import com.example.mybatis.mapping.MappedStatement;
import com.example.mybatis.session.ResultHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class PreparedStatementHandler extends BaseStatementHandler{

    public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, ResultHandler resultHandler, BoundSql boundSql) {
        super(executor, mappedStatement, parameterObject, resultHandler, boundSql);
    }

    /**
    * @Description: 获取SQL 并开启SQL预处理
    * @Param:
    * @return:
    * @Date: 6/4/2024
    */
    @Override
    protected Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }

    /**
    * @Description: 对参数的填充
    * @Param:
    * @return:
    * @Date: 6/4/2024
    */
    @Override
    public void parameterize(Statement statement) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.setLong(1, Long.parseLong(((Object[]) parameterObject)[0].toString()));
    }

    /**
    * @Description: 执行查询与结果封装
    * @Param:
    * @return:
    * @Date: 6/4/2024
    */
    @Override
    public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.<E> handleResultSets(ps);
    }

}
